/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.event;

import entity.ActivityAddressEntity;
import entity.ActivityEntity;
import entity.ActivityOrganiserEntity;
import entity.EventEntity;
import entity.EventTimeEntity;
import entity.Ticket;
import exception.ExistException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.FlowEvent;
import session.stateless.EventSessionBean;
import session.stateless.StaffAccountSessionBean;
import session.stateless.StakeholderSessionBeanStateless;
import session.stateless.SystemMessagesBean;
import util.entityhelper.StakeholderAccountState;
import util.enumeration.ActivityType;
import util.localization.WebLocalization;

/**
 *
 * @author KohLi
 */
@ManagedBean
@ViewScoped
public class ManageEventManagedBean {

    private EventEntity eventActivity;
    private ActivityEntity activity;
    private EventTimeEntity eventTime;
    private Ticket ticket;
    private ActivityOrganiserEntity organiser;
    private ActivityAddressEntity address;
    private Long stakeholderId;
    private Long staffAccountId;
    private String nextPage;
    private FacesContext ctx = FacesContext.getCurrentInstance();
    @EJB
    private EventSessionBean eventSessionBean;
    @EJB
    private SystemMessagesBean systemMessages;
    @EJB
    private StakeholderSessionBeanStateless stakeholderSessionBeanStateless;
    @EJB
    private StaffAccountSessionBean staffSessionBean;
    private String preferredLocale;
    private WebLocalization localization;
    private StakeholderAccountState stakeholder;
    private ActivityType activityType;
    private boolean skip;
    private static Logger logger = Logger.getLogger(EventEntity.class.getName());

    /** Creates a new instance of ManageEventManagedBean */
    public ManageEventManagedBean() {
        // get account ID values from session
        if (ctx.getExternalContext().getSessionMap().containsKey("stakeholderId")) {
            stakeholderId = (Long) ctx.getExternalContext().getSessionMap().get("stakeholderId");
            // put back the session IDs taken
            ctx.getExternalContext().getSessionMap().put("stakeholderId", stakeholderId);
        } else if (ctx.getExternalContext().getSessionMap().containsKey("staffAccountId")) {
            // get session values
            staffAccountId = (Long) ctx.getExternalContext().getSessionMap().get("staffAccountId");
            // put back session values
            ctx.getExternalContext().getSessionMap().put("staffAccountId", staffAccountId);
        } else {
            // redirect back to login
        }
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */


        ticket = new Ticket();
        eventActivity = new EventEntity();
        eventTime = new EventTimeEntity();
        organiser = new ActivityOrganiserEntity();
        address = new ActivityAddressEntity();

    }

    public void initView(PhaseEvent event) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        FacesContext.getCurrentInstance().getExternalContext().getFlash().clear();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (stakeholderId != null && organiser.getOrganisationName() == null) {
            try {
                stakeholder = stakeholderSessionBeanStateless.getStakeholderPortalInfoById(stakeholderId);
                System.out.println("initView: " + stakeholder.getUsername());
                organiser.setOrganisationName(stakeholder.getCorpName());
                organiser.setOrganisationDesc(stakeholder.getStakeholderDesc());
                organiser.setStakeholder(true);
                //eventActivity.setOrganiser(organiser);
            } catch (ExistException ex) {
                System.out.println(" + " + ex.getMessage());
            }
        } else if (staffAccountId != null) {
            eventActivity.setCreator("STAFF_" + staffAccountId);

        }

        if (stakeholderId == null) {

            nextPage = (FacesContext.getCurrentInstance().getExternalContext().encodeActionURL(FacesContext.getCurrentInstance().getApplication().getViewHandler().getActionURL(FacesContext.getCurrentInstance(), "/StakeholderLogin.xhtml")));
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(nextPage);
            } catch (IOException ex) {
                Logger.getLogger(ManageEventManagedBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
        }

    }

    public void handleImageUpload(FileUploadEvent event) throws AbortProcessingException, NoSuchAlgorithmException {

        try {
            String filePath =
                    FacesContext.getCurrentInstance().getExternalContext().getRealPath("images/ads");
            System.out.println("filePath is: " + filePath);
            File result = new File(filePath + System.getProperty("file.separator") + event.getFile().getFileName());
            FileOutputStream out = new FileOutputStream(result);

            int a;
            int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];

            InputStream is = event.getFile().getInputstream();

            while (true) {
                a = is.read(buffer);

                if (a < 0) {
                    break;
                }

                out.write(buffer, 0, a);
                out.flush();
            }

            out.close();
            is.close();

            String imgUrl = "/images/" + event.getFile().getFileName();
            eventActivity.setEventUrl(imgUrl);
            System.out.println("imagefilepath: " + imgUrl);
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);

        } catch (IOException e) {
            FacesContext.getCurrentInstance().addMessage("", new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void saveEvent(ActionEvent event) {
        //check date

        String statusMessage = "";
        Long eventId;


        try {
            //check activity is null or not

            eventSessionBean.saveEvent(eventActivity, activity, address, activityType, organiser, ticket, eventTime);

            System.out.println("what is the activity Type" + activityType);
            System.out.println("address" + address.getBlkNumber() + address.getBuildingName() + address.getStreetName() + address.getPostalCode());

            statusMessage = systemMessages.getSystemMessage("EVENT_SUCCESS", preferredLocale);


            //ctx.getExternalContext().getSessionMap().put("eventId", eventId);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("successmsg", statusMessage);
            //System.out.println("eventId" +eventId);
            redirectPage();
        } catch (ExistException ex) {
            statusMessage = systemMessages.getSystemMessage(ex.getMessage(), preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, ""));
            System.out.println("" + ex.getMessage());
        }
    }

    public String onFlowProcess(FlowEvent event) {
        logger.info("Current wizard step:" + event.getOldStep());
        logger.info("Next step:" + event.getNewStep());

        if (skip) {
            skip = false;   //reset in case user goes back  
            return "confirm";
        } else {
            return event.getNewStep();
        }
    }

    public void redirectPage() {


        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("stakeholderId", stakeholderId);
        FacesContext ctx = FacesContext.getCurrentInstance();
        String nextPage = ctx.getExternalContext().encodeActionURL(ctx.getApplication().getViewHandler().
                getActionURL(ctx, "/common/ViewAllEvent.xhtml"));
        try {
            ctx.getExternalContext().redirect(nextPage);
        } catch (IOException ex) {
            //file dont exist.
        }

    }

    /**
     * @return the eventActivity
     */
    public EventEntity getEvent() {
        return eventActivity;
    }

    /**
     * @param eventActivity the eventActivity to set
     */
    public void setEvent(EventEntity event) {
        this.eventActivity = event;
    }

    /**
     * @return the stakeholderId
     */
    public Long getStakeholderId() {
        return stakeholderId;
    }

    /**
     * @param stakeholderId the stakeholderId to set
     */
    public void setStakeholderId(Long stakeholderId) {
        this.stakeholderId = stakeholderId;
    }

    /**
     * @return the nextPage
     */
    public String getNextPage() {
        return nextPage;
    }

    /**
     * @param nextPage the nextPage to set
     */
    public void setNextPage(String nextPage) {
        this.nextPage = nextPage;
    }

    /**
     * @return the eventSessionBean
     */
    public EventSessionBean getEventSessionBean() {
        return eventSessionBean;
    }

    /**
     * @param eventSessionBean the eventSessionBean to set
     */
    public void setEventSessionBean(EventSessionBean eventSessionBean) {
        this.eventSessionBean = eventSessionBean;
    }

    /**
     * @return the systemMessages
     */
    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    /**
     * @param systemMessages the systemMessages to set
     */
    public void setSystemMessages(SystemMessagesBean systemMessages) {
        this.systemMessages = systemMessages;
    }

    /**
     * @return the preferredLocale
     */
    public String getPreferredLocale() {
        return preferredLocale;
    }

    /**
     * @param preferredLocale the preferredLocale to set
     */
    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    /**
     * @return the localization
     */
    public WebLocalization getLocalization() {
        return localization;
    }

    /**
     * @param localization the localization to set
     */
    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }

    /**
     * @return the stakeholder
     */
    public StakeholderAccountState getStakeholder() {
        return stakeholder;
    }

    /**
     * @param stakeholder the stakeholder to set
     */
    public void setStakeholder(StakeholderAccountState stakeholder) {
        this.stakeholder = stakeholder;
    }

    /**
     * @return the eventTime
     */
    public EventTimeEntity getEventTime() {
        return eventTime;
    }

    /**
     * @param eventTime the eventTime to set
     */
    public void setEventTime(EventTimeEntity eventTime) {
        this.eventTime = eventTime;
    }

    /**
     * @return the ticket
     */
    public Ticket getTicket() {
        return ticket;
    }

    /**
     * @param ticket the ticket to set
     */
    public void setTicket(Ticket ticket) {
        this.ticket = ticket;
    }

    /**
     * @return the staffAccountId
     */
    public Long getStaffAccountId() {
        return staffAccountId;
    }

    /**
     * @param staffAccountId the staffAccountId to set
     */
    public void setStaffAccountId(Long staffAccountId) {
        this.staffAccountId = staffAccountId;
    }

    /**
     * @return the organiser
     */
    public ActivityOrganiserEntity getOrganiser() {
        return organiser;
    }

    /**
     * @param organiser the organiser to set
     */
    public void setOrganiser(ActivityOrganiserEntity organiser) {
        this.organiser = organiser;
    }

    /**
     * @return the address
     */
    public ActivityAddressEntity getAddress() {
        return address;
    }

    /**
     * @param address the address to set
     */
    public void setAddress(ActivityAddressEntity address) {
        this.address = address;
    }

    /**
     * @return the activityType
     */
    public ActivityType getActivityType() {
        return activityType;
    }

    /**
     * @param activityType the activityType to set
     */
    public void setActivityType(ActivityType activityType) {
        this.activityType = activityType;
    }

    public ActivityEntity getActivity() {
        return activity;
    }

    public void setActivity(ActivityEntity activity) {
        this.activity = activity;
    }
}
